package com.pktechan.api.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.pktechan.api.entity.CustBase;
import com.pktechan.api.service.CustBaseService;
import com.pktechan.api.service.RedisService;
import com.pktechan.api.utils.HtmlUtil;
import com.pktechan.api.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * @program: cloudfloating
 * @description: 登录拦截器
 * @author: qx.zhang
 * @create: 2021-03-08 14:55
 **/
public class CommonInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(CommonInterceptor.class);

    @Autowired
    private RedisService redisService;
    @Autowired
    private CustBaseService custBaseService;

    public CommonInterceptor() {
    }

    /**
     * 在业务处理器处理请求之前被调用
     * 如果返回false
     * 从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链
     * 如果返回true
     * 执行下一个拦截器,直到所有的拦截器都执行完毕
     * 再执行被拦截的Controller
     * 然后进入拦截器链,
     * 从最后一个拦截器往回执行所有的postHandle()
     * 接着再从最后一个拦截器往回执行所有的afterCompletion()
     * <p>
     * 微信登录拦截器，微信登录后，保存 t_cust_login_account基本信息、（id、wx_union_id、wx_head_image_url、wx_nickname、status、create_time）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userLoginState = request.getParameter("userLoginState");
        logger.debug("userLoginState-----debug--" + userLoginState);
        if (StringUtil.isValid(userLoginState)) {
            //获取用户登录信息
            HashMap<String, String> loginStateMap = (HashMap<String, String>) redisService.getLoginState(userLoginState);
            if (loginStateMap != null && loginStateMap.containsKey("openid")) {
                String openId = loginStateMap.get("openid");
                logger.debug("用户openId：" + openId);
                String unionId = loginStateMap.get("unionid");
                CustBase custBase = JSONObject.parseObject(redisService.getCustBaseByOpenId(openId), CustBase.class);
                if (custBase != null) {
                    logger.debug("用户openId：" + openId + "--------unionId：" + unionId);
                    return true;
                } else {
                    //redis中不存在客户基本信息。查询数据库
                    custBase = custBaseService.getByOpenId(openId);
                    if (custBase == null) {
                        //数据库未查询出客户信息，说明客户未完成注册。保存微信信息至redis中
                        String wxNickname = request.getParameter("wxNickname");
                        String wxHeadImageUrl = request.getParameter("wxHeadImageUrl");
                        //未创建登录信息，则保存到客户登录信息表中
                        custBase = new CustBase();
                        custBase.setUnionId(unionId);
                        custBase.setOpenId(openId);
                        custBase.setHeadImgUrl(wxHeadImageUrl);
                        custBase.setNickname(wxNickname);
                        custBase.setVipType(0);
                    }
                    redisService.setCustBaseByOpenId(custBase.getOpenId(), JSONObject.toJSONString(custBase));
                    return true;
                }
            } else {
                logger.debug("未查询到登录信息，非法调用接口");
                return false;
            }
        } else {
            logger.debug("参数不合法，非法调用接口");
            HtmlUtil.writerFailJson(response, "参数不合法，非法调用接口");
            return false;
        }

    }

    /**
     * 在业务处理器处理请求执行完成后,生成视图之前执行的动作
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    /**
     * 在DispatcherServlet完全处理完请求后被调用
     * 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion()
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        /*log.info("==============执行顺序: 3、afterCompletion================");*/
    }

}
